<template>
  <div>
    <!-- 条件查询 -->
    <div class="block">
      <span class="demonstration">是否显示</span>
      <el-select v-model="searchEntity.status" placeholder="请选择">
        <el-option label="请选择" value=""></el-option>
        <el-option label="关闭" :value="1"></el-option>
        <el-option label="开启" :value="0"> </el-option>
      </el-select>
      &emsp;&emsp;&emsp;
      <span class="demonstration">秒杀名称:</span>
      <el-input placeholder="请输入秒杀名称" style="width: 250px" v-model="searchEntity.deployName"></el-input>
      <el-button type="primary" round @click="getDeployList()">查询</el-button>
    </div>
    <el-button @click="addCategory()" type="primary" size="small">新增配置</el-button>

    <!-- 表格 -->
    <el-table :data="deployList" style="width: 100%" row-key="id" border lazy
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
      <el-table-column prop="id" label="ID"> </el-table-column>
      <el-table-column prop="deployName" label="秒杀名称"> </el-table-column>
      <el-table-column prop="startTime" label="时间">
        <template slot-scope="scope">
          {{ scope.row.startTime }}-{{ scope.row.endTime }}
        </template>
      </el-table-column>
      <el-table-column prop="imgUrl" label="轮播图片">
        <template slot-scope="scope">
          <span v-for="item in scope.row.deployImg">
            <el-image style="width: 100px; height: 100px" :src="item"></el-image>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="显示状态">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-color="rgba(67, 129, 230, 1)" inactive-color="#ff4949"
            :active-value="0" :inactive-value="1" @change="changeStatus($event, scope.row, scope.$index)">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button @click="updateCategory(scope.row.id)" type="text" size="small">编辑</el-button>
          <el-button type="text" v-if="scope.row.children == null" size="small" @click="deleteById(scope.row.id)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <el-pagination @size-change="reloadList(num)" @current-change="reloadList(num)"
        :current-page.sync="searchEntity.page" :page-sizes="[10, 20, 30, 40]" :page-size.sync="searchEntity.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 新增Form -->
    <el-dialog title="添加数据" :rules="rules" :visible.sync="dialogFormVisible">
      {{deploy}}
      <el-form :model="deploy" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="秒杀名称" prop="deployName">
          <el-input v-model="deploy.deployName"></el-input>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-time-picker v-model="deploy.startTime" value-format="HH:mm:ss" placeholder="任意时间点">
          </el-time-picker>
          <el-time-picker arrow-control v-model="deploy.endTime" value-format="HH:mm:ss" placeholder="任意时间点">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="幻灯片" prop="imgUrl">
          <el-upload action="http://localhost:8001/coco/third/oss/uploadImg" list-type="picture-card" :headers="headers"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleBannerList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="deploy.status" active-text="开启" inactive-text="关闭" active-color="#13ce66"
            :active-value="0" :inactive-value="1" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitCategory('deploy')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 修改Form -->
    <el-dialog title="编辑数据" :rules="rules" :visible.sync="dialogFormVisible2">
      <el-form :model="deploy" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <el-form-item label="秒杀名称" prop="deployName">
          <el-input v-model="deploy.deployName"></el-input>
        </el-form-item>
        <el-form-item label="时间范围" required>
          <el-time-picker v-model="deploy.startTime" value-format="HH:mm:ss" placeholder="任意时间点">
          </el-time-picker>
          <el-time-picker arrow-control v-model="deploy.endTime" value-format="HH:mm:ss" placeholder="任意时间点">
          </el-time-picker>
        </el-form-item>
        <el-form-item label="幻灯片">
          <el-upload action="http://localhost:8001/coco/third/oss/uploadImg" list-type="picture-card"
            :file-list="fileList" :headers="headers" :on-preview="handlePictureCardPreview" :on-remove="handleRemove"
            :on-success="handleBannerList">
            <i class="el-icon-plus"></i>
          </el-upload>
          <el-dialog :visible.sync="dialogVisible">
            <img width="100%" :src="dialogImageUrl" alt="">
          </el-dialog>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-switch v-model="deploy.status" active-text="开启" inactive-text="关闭" active-color="#13ce66"
            :active-value="0" :inactive-value="1" inactive-color="#ff4949">
          </el-switch>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="doUpdateDeploy('deploy')">提交</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
export default {
  // import 引入的组件需要注入到对象中才能使用
  components: {},
  props: {},
  data () {
    // 这里存放数据
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      token: "",
      dialogImageUrl: "",
      imgUrl: "",
      deployList: [], //存放集合
      deploy: {
        imgList: [],
        //添加对象
        status: "0",
      },
      fileList: [],
      searchEntity: {
        limit: 10,
        page: 1,
      },
      total: 0,
      num: 1,
      rules: {
        name: [
          { required: true, message: "请输入秒杀名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        name: [{ required: true, message: "请输入时间范围", trigger: "blur" }],
      },
      dialogFormVisible: false,
      dialogFormVisible2: false,
    };
  },
  // 计算属性 类似于 data 概念
  computed: {
    headers () {
      return {
        "token": (localStorage.token || ""),
        "type": "1"
      }
    }
  },
  // 监控 data 中的数据变化
  watch: {},
  // 方法集合
  methods: {
    handleBannerList (res, file) {//成功上传回调
      this.deploy.imgList.push(res);
    },
    handleRemove (file, fileList) {//删除回调
      console.log(file, fileList);
      this.deploy.imgList.splice(this.deploy.imgList.indexOf(file.response), 1);
    },
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.deploy.imgList.push(file.url);
      console.log(file.url);
      this.dialogVisible = true;
    },
    doUpdateDeploy () {
      //修改
      //修改
      this.$http
        .post("http://localhost:8001/coco/seck/deploy/updateDeploy", this.deploy, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: "修改配置成功!",
              type: "success",
            });
            this.getDeployList();
            this.dialogFormVisible2 = false;
          } else {
            this.$message.error("修改配置失败!");
          }
        })
        .catch((err) => { });
    },
    changeStatus (data, row, index) {
      //显示状态
      console.log(data, row, index);
      this.$http
        .put(
          "http://localhost:8001/coco/seck/deploy/updateStatus/" +
          row.id +
          "/" +
          data, {}, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        }
        )
        .then(({ data }) => {
          console.log(data);
          if (data.code == 0) {
            this.$message({
              message: "修改成功!",
              type: "success",
            });
            this.reloadList(this.num);
          } else {
            let newData = b;
            newData.publishStatus = newData.publishStatus == 1 ? "0" : "1";
            this.goodsList[index] = newData;
          }
        })
        .catch((err) => { });
    },
    submitCategory () {
      //添加
      //创建新配置
      this.$http
        .post("http://localhost:8001/coco/seck/deploy/addDeploy", this.deploy, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: "添加配置成功!",
              type: "success",
            });
            this.getDeployList();
            this.dialogFormVisible = false;
          } else {
            this.$message.error("添加配置失败!");
          }
        })
        .catch((err) => { });
    },
    deleteById (id) {
      //删除
      // 删除
      this.$confirm("此操作将永久删除该秒杀配置, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.$http
          .delete("http://localhost:8001/coco/seck/deploy/deleteById/" + id, {
            headers: {
              "token": this.token,
              "type": "1"
            }
          })
          .then(({ data }) => {
            if (data.code == 0) {
              this.$message({
                message: "删除分类成功!",
                type: "success",
              });
              this.getDeployList();
            } else {
              this.$message.error("删除分类失败!");
            }
          })
          .catch((err) => { });
      });
    },
    updateCategory (id) {
      //修改
      // 修改配置
      this.dialogFormVisible2 = true;
      this.$http
        .get("http://localhost:8001/coco/seck/deploy/selectById/" + id, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        })
        .then(({ data }) => {
          this.deploy = data.data;
          this.deploy.imgList = [];
          this.fileList = JSON.parse(data.data.deployImg).map(item => {
            var obj = {};
            obj.url = item;
            this.deploy.imgList.push(item);
            return obj;
          });
          console.log(this.deploy);
          this.imgUrl = data.data.deployImg;
        })
        .catch((err) => { });
    },
    addCategory () {
      //添加弹窗
      //新增配置
      //打开添加弹窗
      this.dialogFormVisible = true;
      this.deploy = {
        imgList: [],
        //添加对象
        status: "0",
      }
    },
    getDeployList () {
      //列表
      //获取秒杀配置列表
      this.$http
        .post(
          "http://localhost:8001/coco/seck/deploy/findDeployList",
          this.searchEntity, {
          headers: {
            "token": this.token,
            "type": "1"
          }
        }
        )
        .then(({ data }) => {
          console.log(data);
          if (data.code != 0) {
            this.$message({
              message: data.message,
              type: 'error'
            })
            this.$router.push("/");
          }
          this.deployList = data.data.rows;
          this.deployList.forEach(item => {
            item.deployImg = JSON.parse(item.deployImg);
            console.log(item.deployImg);
          })
          this.total = data.data.total;
        })
        .catch((err) => { });
    },
    beforeAvatarUpload (file) {
      //上传前
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 1;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 1MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess (res, file) {
      //上传成功回调
      console.log(res);
      this.imgUrl = res;
      this.deploy.deployImg = this.imgUrl;
    },
  },

  // 生命周期 - 创建完成（可以访问当前 this 实例）
  created () {
    this.token = localStorage.getItem("token");
    this.getDeployList();
  },
  // 生命周期 - 挂载完成（可以访问 DOM 元素）
  mounted () { },
  beforeCreate () { }, // 生命周期 - 创建之前
  beforeMount () { }, // 生命周期 - 挂载之前
  beforeUpdate () { }, // 生命周期 - 更新之前
  updated () { }, // 生命周期 - 更新之后
  beforeDestroy () { }, // 生命周期 - 销毁之前
  destroyed () { }, // 生命周期 - 销毁完成
  activated () { }, // 如果页面有 keep-alive 缓存功能，这个函数会触发
};
</script>

<style>
</style>